package com.lx.shopping.web;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lx.bean.Result;
import com.lx.bilibili.entity.Order;
import com.lx.bilibili.entity.Product;
import com.lx.shopping.biz.impl.PayService;
import com.lx.shopping.dao.OrderMapper;
import com.lx.shopping.dao.ProductExMapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;

/**
 *  支付宝支付，控制器
 *
 * @author chill
 * */
@RestController
@RequestMapping(value = "/pay")
@AllArgsConstructor
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    ProductExMapper productExMapper;

    @Autowired
    OrderMapper orderMapper;

    /**
     *  下单支付
     * */
    @PostMapping(value = "/saveOrder")
    public Object pay (@RequestBody Order order) throws Exception {
        try {
            LambdaUpdateWrapper<Product> luw = new LambdaUpdateWrapper<>();
            luw.eq(Product::getId,order.getPid()).setSql("nums = nums - " + order.getNums());
            productExMapper.update(luw);
            order.setOrdertime( new Timestamp(System.currentTimeMillis()));
            System.out.println("order = " + order);
            if (orderMapper.insert(order) > 0) {
                Object pay = payService.createOrder(order, "购买商品");
                return new Result(1, "购买成功", pay);
            }else{
                return new Result(0, "购买失败，请稍后再试", null);
            }
        } catch (Exception e) {
            // 发生异常时重置自增序列
            Integer nextVal = orderMapper.getNextAutoIncrementValue();
            orderMapper.setAutoIncrement(nextVal != null ? nextVal : 1);
            throw e;
        }
        //这个接口其实应该是post方式的，但是我这里图方便，直接以get方式访问，
        //且返回格式是text/html，这样前端页面就能直接显示支付宝返回的html片段
        //真实场景下由post方式请求，返回code、msg、data那种格式的标准结构，让前端拿到data里的
        //html片段之后自行加载

        //由于我这里并没有真正的传参数，所以象征性的new一下，避免空指针
    }
}

